const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

class CacheManager {
    constructor(cacheDir = './.filecache') {
        this.cacheDir = cacheDir;
        this.memoryCache = new Map();
        this.ensureCacheDir();
    }

    ensureCacheDir() {
        if (!fs.existsSync(this.cacheDir)) {
            fs.mkdirSync(this.cacheDir, { recursive: true });
        }
    }

    // 生成缓存键（基于路径和模式）
    generateCacheKey(vaultPath, patterns) {
        return crypto.createHash('md5')
            .update(vaultPath + patterns.join(","))
            .digest('hex');
    }

    // 检查缓存有效性
    async isCacheValid(cacheKey, vaultPath) {
        const cacheFile = path.join(this.cacheDir, `${cacheKey}.json`);

        try {
            const stats = await fs.promises.stat(cacheFile);
            const vaultStats = await fs.promises.stat(vaultPath);

            // 检查vault是否修改过
            return stats.mtime >= vaultStats.mtime;
        } catch {
            return false;
        }
    }

    // 获取缓存
    async getCache(cacheKey) {
        if (this.memoryCache.has(cacheKey)) {
            return this.memoryCache.get(cacheKey);
        }

        const cacheFile = path.join(this.cacheDir, `${cacheKey}.json`);
        try {
            const data = await fs.promises.readFile(cacheFile, 'utf8');
            const result = JSON.parse(data);
            this.memoryCache.set(cacheKey, result);
            return result;
        } catch {
            return null;
        }
    }

    async setCache(cacheKey, data) {
        const cacheFile = path.join(this.cacheDir, `${cacheKey}.json`);
        try {
            await fs.promises.writeFile(cacheFile, JSON.stringify(data, null, 2));
            this.memoryCache.set(cacheKey, data);
        } catch (error) {
            console.error('Failed to write cache:', error);
        }
    }
}

module.exports = CacheManager;